//
//  EconomicCalendarViewController.m
//  BondWatch
//
//  Created by Jason Yuan on 11/25/15.
//  Copyright © 2015 Jason Yuan. All rights reserved.
//

#import "EconomicCalendarViewController.h"
#import "EconomicCalendarTableViewCell.h"

@interface EconomicCalendarViewController () <UITableViewDelegate, UITableViewDataSource>
{
    UIScrollView *myScrollView;
    UITableView *myTableView;
    NSArray *dataArray;
}

@end

@implementation EconomicCalendarViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self getData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"Economic Calendar";
    
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys: [UIFont fontWithName:@"Helvetica-Bold" size:18.0],NSFontAttributeName, nil]];
    
    UIBarButtonItem *settingBarButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Settings"] style:UIBarButtonItemStylePlain target:self action:@selector(settingBarButtonItemPressed:)];
    self.navigationItem.leftBarButtonItem = settingBarButton;
    
    UIBarButtonItem *refreshBarButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Refresh"] style:UIBarButtonItemStylePlain target:self action:@selector(refreshBarButtonPressed:)];
    self.navigationItem.rightBarButtonItem = refreshBarButton;
    
    myScrollView = [[UIScrollView alloc] init];
    myScrollView.bounces = NO;
    [self.view addSubview:myScrollView];
    
    
    myScrollView.contentSize = CGSizeMake(500.0, 0);
    
    myTableView = [[UITableView alloc] init];
    if ([UIApplication sharedApplication].statusBarOrientation == UIDeviceOrientationLandscapeLeft ||
        [UIApplication sharedApplication].statusBarOrientation == UIDeviceOrientationLandscapeRight) {
        myTableView.frame = CGRectMake(0.0, 0.0, self.view.bounds.size.width, self.view.bounds.size.height - 30);
    } else {
        myTableView.frame = CGRectMake(0, 0, 500, self.view.bounds.size.height - 64);
    }
    myTableView.delegate = self;
    myTableView.dataSource = self;
    myTableView.bounces = NO;
    myTableView.separatorInset = UIEdgeInsetsZero;
    myTableView.layoutMargins = UIEdgeInsetsZero;
    [myScrollView addSubview:myTableView];
    
    [myScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.top.equalTo(self.view);
        make.bottom.equalTo(self.view);
    }];
}

- (void)settingBarButtonItemPressed:(id)sender {
    [self.mm_drawerController toggleDrawerSide:MMDrawerSideLeft animated:YES completion:nil];
}

- (void)refreshBarButtonPressed:(id)sender {
    [self getData];
}

- (void)getData {
    [MBProgressHUD showHUDAddedTo:self.view animated:YES].dimBackground = YES;
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = 100.0f;
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    [manager GET:ECONOMICCALENDARURL parameters:nil success:^(NSURLSessionDataTask *task, id JSON) {
        
        NSString *string = [[NSString alloc] initWithData:JSON encoding:NSUTF8StringEncoding];
        dataArray = [string objectFromJSONString];
        DDLogVerbose(@"Economic Calendar error:\n%@", dataArray);
        [myTableView reloadData];
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
        if (response.statusCode == 200) {
            [self.navigationController dismissViewControllerAnimated:YES completion:nil];
            return;
        }
        
        DDLogError(@"Get Economic Calendar error:\n%@", error);
        NSString *result = [[NSString alloc] initWithData:[error.userInfo objectForKey:@"com.alamofire.serialization.response.error.data"] encoding:NSUTF8StringEncoding];
        DDLogError(@"Get Economic Calendar error Message:\n%@", result);
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Setting Rotate

- (BOOL)shouldAutorotate {
    return YES;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskAll;
}

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
    if (toInterfaceOrientation == UIDeviceOrientationLandscapeRight ||
        toInterfaceOrientation == UIDeviceOrientationLandscapeLeft) {
        myTableView.frame = CGRectMake(0.0, 0.0, self.view.bounds.size.width, self.view.bounds.size.height - 30);
    } else {
        myTableView.frame = CGRectMake(0, 0, 500, self.view.bounds.size.height - 64);
    }
    [myTableView reloadData];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    if (![dataArray isEqual:[NSNull null]]) {
        return [dataArray count];
    } else {
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    EconomicCalendarTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"EconomicCalendar"];
    
    // Configure the cell...
    if (cell == nil) {
        cell = [[EconomicCalendarTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MarketDetail"];
        cell.separatorInset = UIEdgeInsetsZero;
    }
    NSDictionary *dictionary = [dataArray objectAtIndex:indexPath.row];
    
    [cell setUIFrame];
    if (indexPath.row < [dataArray count]) {
        [cell setLabelText:dictionary];
    }
    
    return cell;
}

// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}

// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    cell.separatorInset = UIEdgeInsetsZero;
    cell.layoutMargins = UIEdgeInsetsZero;
}

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

#pragma mark - Table view delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 30.0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleNone;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 30.0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 500.0, 30.0)];
    [headerView setBackgroundColor:[UIColor colorWithRed:239.0/255.0 green:239.0/255.0 blue:239.0/255.0 alpha:1.0]];
    
    UILabel *dateTimeLabel;
    UILabel *eventLabel;
    UILabel *periodLabel;
    UILabel *surveyLabel;
    UILabel *actualLabel;
    UILabel *proirLabel;
    UILabel *revisedLabel;
    
    dateTimeLabel = [[UILabel alloc] init];
    dateTimeLabel.textAlignment = NSTextAlignmentLeft;
    dateTimeLabel.font = ARIALBOLD10;
    dateTimeLabel.text = @"DateTime";
    dateTimeLabel.textColor = [UIColor blueColor];
    
    eventLabel = [[UILabel alloc] init];
    eventLabel.textAlignment = NSTextAlignmentLeft;
    eventLabel.font = ARIALBOLD10;
    eventLabel.text = @"Event";
    eventLabel.textColor = [UIColor blueColor];
    
    periodLabel = [[UILabel alloc] init];
    periodLabel.textAlignment = NSTextAlignmentLeft;
    periodLabel.font = ARIALBOLD10;
    periodLabel.text = @"Period";
    periodLabel.textColor = [UIColor blueColor];
    
    surveyLabel = [[UILabel alloc] init];
    surveyLabel.textAlignment = NSTextAlignmentLeft;
    surveyLabel.font = ARIALBOLD10;
    surveyLabel.text = @"Survey";
    surveyLabel.textColor = [UIColor blueColor];
    
    actualLabel = [[UILabel alloc] init];
    actualLabel.textAlignment = NSTextAlignmentLeft;
    actualLabel.font = ARIALBOLD10;
    actualLabel.text = @"Actual";
    actualLabel.textColor = [UIColor blueColor];
    
    proirLabel = [[UILabel alloc] init];
    proirLabel.textAlignment = NSTextAlignmentLeft;
    proirLabel.font = ARIALBOLD10;
    proirLabel.text = @"Proir";
    proirLabel.textColor = [UIColor blueColor];
    
    revisedLabel = [[UILabel alloc] init];
    revisedLabel.textAlignment = NSTextAlignmentLeft;
    revisedLabel.font = ARIALBOLD10;
    revisedLabel.text = @"Revised";
    revisedLabel.textColor = [UIColor blueColor];
    
    [headerView addSubview:dateTimeLabel];
    [headerView addSubview:eventLabel];
    [headerView addSubview:periodLabel];
    [headerView addSubview:surveyLabel];
    [headerView addSubview:actualLabel];
    [headerView addSubview:proirLabel];
    [headerView addSubview:revisedLabel];
    
    [dateTimeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(headerView).offset(2);
        make.centerY.equalTo(headerView);
        make.width.mas_equalTo(80);
    }];
    
    [eventLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(dateTimeLabel.mas_right).offset(5);
        make.centerY.equalTo(headerView);
        make.width.mas_equalTo(160);
    }];
    
    [periodLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(eventLabel.mas_right).offset(5);
        make.centerY.equalTo(headerView);
        make.width.mas_equalTo(40);
    }];
    
    [surveyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(periodLabel.mas_right).offset(5);
        make.centerY.equalTo(headerView);
        make.width.mas_equalTo(40);
    }];
    
    [actualLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(surveyLabel.mas_right).offset(5);
        make.centerY.equalTo(headerView);
        make.width.mas_equalTo(40);
    }];
    
    [proirLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(actualLabel.mas_right).offset(5);
        make.centerY.equalTo(headerView);
        make.width.mas_equalTo(40);
    }];
    
    [revisedLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(proirLabel.mas_right).offset(5);
        make.centerY.equalTo(headerView);
        make.width.mas_equalTo(40);
    }];
    
    return headerView;
}

@end
